<template>
  <GridPage title="投递情况" size="full">
    <n-card class="mt-12" title="投递列表">
      <n-data-table
        :columns="resumeSubmissionColumns"
        :data="resumeSubmission"
        :bordered="false"
        max-height="400px"
        :pagination="pagination"
      />
    </n-card>

    <n-card class="mt-12" title="我的面试安排" v-if="!isSeeker">
      <n-data-table
        :columns="interviewColumns"
        :data="interviews"
        :bordered="false"
        max-height="400px"
        :pagination="pagination"
      />
    </n-card>
  </GridPage>

  <MeModal
    ref="arrangeRef"
    title="安排下一步面试"
    width="800px"
    :showCancel="false"
    :showOk="false"
  >
    <n-form ref="arrangeFormRef" :model="arrangeForm" :rules="arrangeRules">
      <n-grid :cols="24" :x-gap="24">
        <n-form-item-gi label="面试轮次" path="step" :span="12">
          <n-select v-model:value="arrangeForm.step" :options="stepOps" :disabled="true" />
        </n-form-item-gi>
        <n-form-item-gi label="面试人员" path="recruiter_id" :span="12">
          <n-select
            v-model:value="arrangeForm.recruiter_id"
            :options="recruiterOps"
            :render-label="renderLabel"
            :render-tag="renderTag"
          />
        </n-form-item-gi>
        <n-form-item-gi label="面试描述" path="description" :span="24">
          <n-input
            v-model:value="arrangeForm.description"
            type="textarea"
            maxlength="100"
            placeholder="填写面试时间、面试地点等"
            show-count
          />
        </n-form-item-gi>
        <n-gi :span="24">
          <n-flex justify="end">
            <n-button type="success" @click="arrangeInterview">确定</n-button>
          </n-flex>
        </n-gi>
      </n-grid>
    </n-form>
  </MeModal>

  <MeModal ref="resultRef" title="填写面试结果" width="800px" :showCancel="false" :showOk="false">
    <n-form ref="resultFormRef" :model="resultForm" :rules="resultRules">
      <n-grid :cols="24" :x-gap="24">
        <n-form-item-gi label="面试结果内容" path="result" :span="24">
          <n-input
            v-model:value="resultForm.result"
            type="textarea"
            maxlength="100"
            placeholder="填写面试结果，录取情况等"
            show-count
          />
        </n-form-item-gi>
        <n-gi :span="24">
          <n-flex justify="end">
            <n-button type="error" @click="failInterview">不通过</n-button>
            <n-button type="success" @click="passInterview">通过面试</n-button>
          </n-flex>
        </n-gi>
      </n-grid>
    </n-form>
  </MeModal>

  <MeModal ref="resumeRef" title="简历详情" width="1000px" :showCancel="false" :showOk="false">
    <n-scrollbar style="max-height: 500px">
      <n-card class="mt-12">
        <n-flex>
          <n-avatar lazy :src="resume.avatar_url" :size="100" round />
          <n-flex vertical>
            <h2>{{ resume.name }}</h2>
            <n-flex>
              <InfoItem icon="i-fe:smile" :value="age"></InfoItem>
              <InfoItem icon="i-fe:user" :value="gender"></InfoItem>
              <InfoItem icon="i-fe:map-pin" :value="address"></InfoItem>
              <InfoItem icon="i-fe:navigation" :value="state"></InfoItem>
            </n-flex>
            <n-flex>
              <InfoItem icon="i-fe:star" :value="identity"></InfoItem>
              <InfoItem icon="i-fe:phone" :value="resume.phone_number"></InfoItem>
              <InfoItem icon="i-fe:mail" :value="resume.email"></InfoItem>
            </n-flex>
          </n-flex>
        </n-flex>
      </n-card>

      <Card title="工作经历" :can-edit="false">
        <WI v-for="item in resume.work_experiences" :data="item" :can-edit="false"></WI>
      </Card>
      <Card title="教育经历" :can-edit="false">
        <EI v-for="item in resume.education_experiences" :data="item" :can-edit="false"></EI>
      </Card>
      <Card title="项目经历" :can-edit="false">
        <PI v-for="item in resume.project_experiences" :data="item" :can-edit="false"></PI>
      </Card>
    </n-scrollbar>
  </MeModal>

  <MeModal ref="progressRef" title="投递进度" width="1000px" :showCancel="false" :showOk="false">
    <n-steps :current="current" :status="currentStatus">
      <n-step title="简历初筛" :description="description[0]" style="white-space: pre" />
      <n-step title="部门面试" :description="description[1]" style="white-space: pre" />
      <n-step title="人事面试" :description="description[2]" style="white-space: pre" />
      <n-step title="最终面试" :description="description[3]" style="white-space: pre" />
    </n-steps>
  </MeModal>
</template>

<script setup>
import { MeModal, GridPage, InfoItem } from '@/components'
import { useModal, useForm } from '@/composables'
import seekerApi from '@/api/seeker'
import recruiterApi from '@/api/recruiter'
import { getCity } from '@/data'
import { useUserStore, useRecruiterStore, useSeekerStore } from '@/store'
import { NButton, NTag } from 'naive-ui'
import Card from '../resume/card.vue'
import WI from '../resume/work/workExperienceItem.vue'
import EI from '../resume/education/educationExperienceItem.vue'
import PI from '../resume/project/projectExperienceItem.vue'
const userStore = useUserStore()

const resultRules = {
  result: { required: true, message: '此为必填项', trigger: ['blur', 'change'] },
}
const arrangeRules = {
  recruiter_id: {
    type: 'number',
    required: true,
    message: '此为必填项',
    trigger: ['blur', 'change'],
  },
  description: { required: true, message: '此为必填项', trigger: ['blur', 'change'] },
}

const pagination = {
  pageSize: 5,
}

//简历投递列表
const resumeSubmission = ref([])
const resume = ref({})

//简历投递面试列表
const interviews = ref([])

//当前用户是否为求职者
const isSeeker = ref(false)

const resumeSubmissionColumns = computed(() => {
  const cols = [
    {
      title: '投递职位',
      align: 'center',
      key: 'title',
      width: '140px',
    },
    {
      title: '求职者姓名',
      align: 'center',
      key: 'name',
      width: '140px',
    },
    {
      title: '投递时间',
      align: 'center',
      key: 'apply_time',
      width: '140px',
      sorter: (a, b) => a.apply_time.localeCompare(b.apply_time),
    },
    {
      title: '投递阶段',
      align: 'center',
      key: 'step',
      width: '140px',
      render(row) {
        const obj = stepOps[row.step]
        return h(
          NTag,
          {
            type: 'primary',
            bordered: false,
          },
          {
            default: () => obj.label,
          }
        )
      },
    },
    {
      title: '投递状态',
      align: 'center',
      key: 'state',
      width: '140px',
      render(row) {
        const obj = states[row.state]
        return h(
          NTag,
          {
            type: obj.type,
            bordered: false,
          },
          {
            default: () => obj.label,
          }
        )
      },
    },
    {
      title: '投递详情',
      align: 'center',
      key: 'detail',
      width: '100px',
      render(row) {
        return h(
          NButton,
          {
            type: 'primary',
            size: 'small',
            onClick: () => handleProgress(row),
          },
          { default: () => '查看详情' }
        )
      },
    },
    {
      title: '简历',
      align: 'center',
      key: 'resume',
      width: isSeeker.value ? 0 : 100,
      render(row) {
        return h(
          NButton,
          {
            type: 'primary',
            size: 'small',
            onClick: () => handleResume(row),
          },
          { default: () => '查看简历' }
        )
      },
    },
    {
      title: '操作',
      align: 'center',
      key: 'action',
      width: isSeeker.value ? 0 : 100,
      render(row) {
        return h(
          NButton,
          {
            type: 'primary',
            size: 'small',
            disabled: row.state !== 0,
            onClick: () => handleArrange(row),
          },
          { default: () => '面试安排' }
        )
      },
    },
  ]
  return cols.filter((e) => e.width)
})

const interviewColumns = ref([
  {
    title: '投递职位',
    align: 'center',
    key: 'title',
  },
  {
    title: '求职者姓名',
    align: 'center',
    key: 'name',
  },
  {
    title: '面试安排描述',
    align: 'center',
    key: 'description',
    render(row) {
      return h(
        NButton,
        {
          type: 'primary',
          size: 'small',
          onClick: () => {
            $dialog.create({
              title: '面试安排描述',
              content: row.description,
              positiveText: '确定',
            })
          },
        },
        { default: () => '查看安排' }
      )
    },
  },
  {
    title: '投递阶段',
    align: 'center',
    key: 'step',
    render(row) {
      const obj = stepOps[row.step]
      return h(
        NTag,
        {
          type: 'primary',
          bordered: false,
        },
        {
          default: () => obj.label,
        }
      )
    },
  },
  {
    title: '投递状态',
    align: 'center',
    key: 'state',
    width: '140px',
    render(row) {
      const obj = interviewStates[row.state]
      return h(
        NTag,
        {
          type: obj.type,
          bordered: false,
        },
        {
          default: () => obj.label,
        }
      )
    },
  },
  {
    title: '简历',
    align: 'center',
    key: 'resume',
    render(row) {
      return h(
        NButton,
        {
          type: 'primary',
          size: 'small',
          onClick: () => handleResume(row),
        },
        { default: () => '查看简历' }
      )
    },
  },
  {
    title: '操作',
    align: 'center',
    key: 'actions',
    render(row) {
      return h(
        NButton,
        {
          type: 'primary',
          size: 'small',
          disabled: row.state !== 0,
          onClick: () => handleResult(row),
        },
        { default: () => '填写结果' }
      )
    },
  },
])

const stepOps = [
  { value: 0, label: '简历初筛' },
  { value: 1, label: '部门面试' },
  { value: 2, label: '人事面试' },
  { value: 3, label: '最终面试' },
]
const states = [
  { value: 0, label: '安排面试', type: 'warning' },
  { value: 1, label: '等待结果', type: 'warning' },
  { value: 2, label: '投递成功', type: 'success' },
  { value: 3, label: '投递失败', type: 'error' },
]
const progressStates = ['process', 'process', 'finish', 'error']
const interviewStates = [
  { value: 0, label: '等待结果', type: 'warning' },
  { value: 1, label: '面试通过', type: 'success' },
  { value: 2, label: '面试失败', type: 'error' },
]
//年龄 计算
let age = computed(() => {
  const now = new Date()
  const birth = new Date(resume.value.birth_date)
  let ret = now.getFullYear() - birth.getFullYear()

  // 检查是否已经过了生日
  if (
    now.getMonth() < birth.getMonth() ||
    (now.getMonth() === birth.getMonth() && now.getDate() < birth.getDate())
  ) {
    ret--
  }
  return ret
})

//性别 计算
let gender = computed(() => {
  if (resume.value.gender === 1) return '男'
  else return '女'
})

//计算地址
let address = computed(() => {
  return getCity(resume.value.address_code)
})

//计算状态
let state = computed(() => {
  const state = resume.value.state
  if (state === 0) return '离校，正在找工作'
  if (state === 1) return '在校，可即刻到岗'
  if (state === 2) return '在校，看看机会'
  else return '在校，暂时不找工作'
})

//计算身份
let identity = computed(() => {
  const identity = resume.value.identity
  if (identity === 0) return '学生'
  if (identity === 1) return '职场人'
})

//招聘人员选择框内容和标签渲染
const renderLabel = (option) => {
  return h(
    'div',
    {
      style: {
        display: 'flex',
        alignItems: 'center',
      },
    },
    [
      h(
        'div',
        {
          style: {
            marginLeft: '10px',
          },
        },
        [option.name]
      ),
      h(
        NTag,
        {
          type: 'primary',
          bordered: false,
          class: ['ml-40'],
        },
        {
          default: () => option.title,
        }
      ),
    ]
  )
}
const renderTag = ({ option }) => {
  return h(
    'div',
    {
      style: {
        display: 'flex',
        alignItems: 'center',
      },
    },
    [
      h(
        'div',
        {
          style: {
            marginLeft: '10px',
          },
        },
        [option.name]
      ),
      h(
        NTag,
        {
          type: 'primary',
          bordered: false,
          class: ['ml-40'],
        },
        {
          default: () => option.title,
        }
      ),
    ]
  )
}
//招聘人员选择列表
const recruiterOps = ref([])

const [resumeRef] = useModal()
const [resultRef] = useModal()
const [progressRef] = useModal()
const [arrangeRef] = useModal()
const [resultFormRef, resultForm, resultValidation] = useForm({})
const [arrangeFormRef, arrangeForm, arrangValidation] = useForm({})

const current = ref()
const currentStatus = ref()
const description = ref([])
const progress = ref([])
let progressList = []
//打开投递进度对话框
async function handleProgress(row) {
  progressRef.value.open()
  if (!progressList.find((e) => e.submission_id === row.submission_id)) {
    const { data } = await recruiterApi.getResumeSubmissionProgress(row.submission_id)
    progressList.push({
      submission_id: row.submission_id,
      data: data,
    })
  }
  progress.value = progressList.find((e) => e.submission_id === row.submission_id).data
  current.value = row.step + 1
  currentStatus.value = progressStates[row.state]
  for (let i = 0; i < 4; i++) {
    const obj = progress.value.find((e) => e.step === i)
    if (!obj) {
      description.value[i] = '暂无信息'
      break
    } else {
      if (obj.state === 0) description.value[i] = obj.description
      else description.value[i] = obj.result
    }
  }
}

//打开查看简历对话框
async function handleResume(row) {
  resumeRef.value.open()
  if (row.seeker_id !== resume.value.seeker_id) {
    const { data } = await seekerApi.getResume(row.seeker_id)
    resume.value = data
  }
}

let resultObj
//打开结果填写对话框
function handleResult(row) {
  resultObj = row
  resultForm.value.result = undefined
  resultRef.value.open()
}
async function passInterview() {
  await resultValidation()
  $dialog.create({
    title: '确定通过面试？',
    content: '此操作不可撤销，请认真操作',
    positiveText: '确定',
    async onPositiveClick() {
      await recruiterApi.passInterview({
        id: resultObj.id,
        submission_id: resultObj.submission_id,
        result: resultForm.value.result,
      })
      $message.success('通过面试成功')
      resultObj.state = 1
      resultRef.value.close()
    },
  })
}
async function failInterview() {
  await resultValidation()
  $dialog.error({
    title: '确定不通过面试？',
    content: '此操作不可撤销，请认真操作',
    positiveText: '确定',
    async onPositiveClick() {
      await recruiterApi.failInterview({
        id: resultObj.id,
        submission_id: resultObj.submission_id,
        result: resultForm.value.result,
      })
      $message.success('不通过面试成功')
      resultObj.state = 2
      resultRef.value.close()
    },
  })
}

let arrangeObj
//打开面试安排对话框
function handleArrange(row) {
  arrangeObj = row
  arrangeForm.value.step = row.step
  arrangeForm.value.recruiter_id = undefined
  arrangeForm.value.description = undefined
  arrangeRef.value.open()
}
async function arrangeInterview() {
  await arrangValidation()
  $dialog.create({
    title: '确定安排面试？',
    content: '此操作不可撤销，请认真操作',
    positiveText: '确定',
    async onPositiveClick() {
      await recruiterApi.arrangeInterview({
        submission_id: arrangeObj.submission_id,
        seeker_id: arrangeObj.seeker_id,
        recruiter_id: arrangeForm.value.recruiter_id,
        job_id: arrangeObj.job_id,
        state: 0,
        step: arrangeForm.value.step,
        description: arrangeForm.value.description,
      })
      $message.success('安排面试成功')
      arrangeObj.state = 1
      arrangeRef.value.close()
    },
  })
}

onMounted(async () => {
  isSeeker.value = userStore.role === 'seeker'
  if (isSeeker.value) {
    const { data } = await seekerApi.getResumeSubmissions(useSeekerStore().seeker.seeker_id)
    resumeSubmission.value = data
  } else {
    const recruiterStore = useRecruiterStore()
    if (recruiterStore.recruiter.company_id !== null) {
      let res = await recruiterApi.getResumeSubmissions(recruiterStore.recruiter.recruiter_id)
      resumeSubmission.value = res.data
      res = await recruiterApi.getCompanyRecruiters(recruiterStore.recruiter.company_id)
      recruiterOps.value = res.data
      recruiterOps.value.forEach((e) => {
        e.label = e.name
        e.value = e.recruiter_id
      })
      res = await recruiterApi.getInterviewArrangements(recruiterStore.recruiter.recruiter_id)
      interviews.value = res.data
    }
  }
})
</script>
